package org.bjf.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author bjf
 */
public class Http {

    public static final String DEFAULT_CHARSET = "UTF-8";
    private static Logger log = LoggerFactory.getLogger(Http.class);
    private static CloseableHttpClient httpClient;
    private static PoolingHttpClientConnectionManager cm;
    private static ResponseHandler<HttpObj> responseHandler = null;

    static {
        //===1.设置ConnectionManager
        cm = new PoolingHttpClientConnectionManager();
        // 最大连接数
        cm.setMaxTotal(50);
        // 每路由的最大连接数，默认值是2
        cm.setDefaultMaxPerRoute(10);
        //剔除过期无效连接
        cm.closeExpiredConnections();
        cm.setValidateAfterInactivity(2000);

        //===2.设置httpClient
        httpClient = HttpClientBuilder.create()
                .useSystemProperties()
                // 线程池
                .setConnectionManager(cm)
                // 请求设置
                .setDefaultRequestConfig(
                        RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build())
                // 超时
                .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(5000).build())
                .build();

        //===3.响应Handler
        responseHandler = new ResponseHandler<HttpObj>() {
            @Override
            public HttpObj handleResponse(HttpResponse httpResponse) throws IOException {
                StatusLine statusLine = httpResponse.getStatusLine();
                HttpEntity entity = httpResponse.getEntity();
                final byte[] bodyBytes;
                if (entity != null) {
                    bodyBytes = EntityUtils.toByteArray(entity);
                } else {
                    bodyBytes = new byte[0];
                }
                HttpObj resp = new HttpObj();
                resp.setStatusCode(statusLine.getStatusCode());
                resp.setBody(new String(bodyBytes, DEFAULT_CHARSET));
                return resp;
            }
        };

        //===4.关闭钩子
        shutdownHook();
    }

    private static void shutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread("thread-http.shutdown") {
            @Override
            public void run() {
                try {
                    httpClient.close();
                } catch (IOException ignore) {
                    log.error("httpClient 关闭失败", ignore);
                }
            }
        });
    }

    public static HttpObj get(String url) {
        return get(url, null);
    }

    public static HttpObj get(String url, Map<String, Object> params) {
        return getHttpObj(url, params, null);
    }

    public static HttpObj get(String url, Map<String, Object> params, Map<String, String> headers) {
        return getHttpObj(url, params, headers);
    }

    public static HttpObj getHttpObj(String url, Map<String, Object> params,
                                     Map<String, String> headers) {

        //===1.组装url
        if (params != null && params.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> param : params.entrySet()) {
                nvps.add(new BasicNameValuePair(param.getKey(), param.getValue().toString()));
            }
            String queryString = URLEncodedUtils.format(nvps, DEFAULT_CHARSET);
            url = url + "?" + queryString;
        }

        HttpGet get = new HttpGet(url);

        return execute(get, headers);
    }


    public static HttpObj post(String url, Map<String, Object> params) {
        return post(url, params, null);
    }

    public static HttpObj post(String url, Map<String, Object> params, Map<String, String> headers) {
        UrlEncodedFormEntity entity = null;
        if (params != null && params.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> param : params.entrySet()) {
                nvps.add(new BasicNameValuePair(param.getKey(), param.getValue().toString()));
            }
            entity = new UrlEncodedFormEntity(nvps, Charset.forName(DEFAULT_CHARSET));
        }
        return post(url, entity, headers);
    }

    public static HttpObj postJson(String url, String body) {
        return postJson(url, body, null);
    }

    public static HttpObj postJson(String url, String body, Map<String, String> headers) {
        StringEntity entity = new StringEntity(body, DEFAULT_CHARSET);
        entity.setContentType("application/json");
        return post(url, entity, headers);
    }

    private static HttpObj post(String url, HttpEntity entity, Map<String, String> headers) {
        HttpPost post = new HttpPost(url);
        if (entity != null) {
            post.setEntity(entity);
        }
        return execute(post, headers);
    }

    private static HttpObj execute(HttpUriRequest req, Map<String, String> headers) {
        //===请求header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                req.setHeader(entry.getKey(), entry.getValue());
            }
        }
        //===traceId
        String traceId = MDC.get("X-B3-TraceId");
        if (StringUtils.isNotBlank(traceId)) {
            req.setHeader("X-B3-TraceId", traceId);
        }
        try {
            return httpClient.execute(req, responseHandler);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {

        //===1.get请求
        String get = Http.get("https://www.baidu.com/").getBody();
        System.out.println("get = " + get);


       /* //===2.post for json
        Map<String, Object> param = new HashMap<>();
        param.put("name", "google");
        String json = JSONObject.toJSONString(param);
        System.out.println("json = " + json);
        String post = Http.postJson("http://localhost:9095/test/add", json);
        System.out.println("post = " + post);

        //===3.post common
        String body = Http.post("http://localhost:9095/test/add", param);
        System.out.println("body = " + body);*/
    }
}
